var curUserId = null;

var conn = null;
var curRoomId = null;
var curChatRoomId = null;
var msgCardDivId = "chat01";
var talkToDivId = "talkTo";
var talkInputId = "talkInputId";
var bothRoster = [];
var toRoster = [];
var maxWidth = 200;
var groupFlagMark = "groupchat";
var chatRoomMark = "chatroom";
var groupQuering = false;
var textSending = false;
var time = 0;
var flashFilename = '';
var audioDom = [];
var picshim;
var audioshim;
var fileshim;
var friendsSub = {};
var PAGELIMIT = 8;
var pageLimitKey = new Date().getTime();

var encode = function ( str ) {
	if ( !str || str.length === 0 ) return "";
	var s = '';
	s = str.replace(/&amp;/g, "&");
	s = s.replace(/<(?=[^o][^)])/g, "&lt;");
	s = s.replace(/>/g, "&gt;");
	// s = s.replace(/\'/g, "&#39;");
	s = s.replace(/\"/g, "&quot;");
	s = s.replace(/\n/g, "<br>");
	return s;
};


var username = '';
var password = '';
var curChatUserId = null;

var nick_name = null;
var head_img = null;

function getQueryString(name) {
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null) { 
    	 return  unescape(r[2]); 
     }
     return null;
}

function getCookie(name) {
	var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
	if(arr=document.cookie.match(reg))
		return unescape(arr[2]);
	else
		return null;
}

//easemobwebim-sdk注册回调函数列表
$(document).ready(function() {
	username = getCookie('anonymous_name');
	password = getCookie('anonymous_password');
	if (username != null && username != '' && password != null && password != '') {
		
	} else {
		// 注册一个环信id
		$.ajax({ 
			type: 'post', 
			url: './anonymousregister', 
			async: false,
			success: function(data) {
				console.log(data);
				if (data.code == 0) {
					username = data.my_id;
					password = data.anonymous_pass;
					document.cookie="anonymous_name=" + username;
		        	document.cookie = "anonymous_password=" + password;
				}
			}
		});
	}
	
	//curChatUserId = getCookie('talk_id');
	curChatUserId = getQueryString('talk_id');
	
	// 获得该用户的昵称和头像
	$.ajax({ 
		type: 'post', 
		url: 'getanonymoushead', 
		async: false, 
		data: {anonymous_id: curChatUserId}, 
		success: function(data) {
			if (data.code == 0) {
				var anonymous = data.anonymous;
				nick_name = anonymous.nick_name;
				if (anonymous.portrait == null || anonymous.portrait == '') {
					head_img = 'static/img/head/header2.jpg';
				} else {
					head_img = 'http://139.196.188.251:8080/upload/cache/' + anonymous.portrait;
				}
			}
		}
	});
	
	if ( Easemob.im.Helper.getIEVersion && Easemob.im.Helper.getIEVersion < 10 ) {
		$('#em-cr').remove();
	}
	
	conn = new Easemob.im.Connection({
		multiResources: Easemob.im.config.multiResources,
		https : Easemob.im.config.https,
		url: Easemob.im.config.xmppURL
	});
	
	// 初始化连接
	conn.listen({
		// 当连接成功时的回调方法
		onOpened : function() {
			handleOpen(conn);
		},
		// 当连接关闭时的回调方法
		onClosed : function() {
			handleClosed();
		},
		// 收到文本消息时的回调方法
		onTextMessage : function(message) {
			handleTextMessage(message);
		},
		// 收到表情消息时的回调方法
		onEmotionMessage : function(message) {
			handleEmotion(message);
		},
		// 收到图片消息时的回调方法
		onPictureMessage : function(message) {
			handlePictureMessage(message);
		},
		// 收到音频消息的回调方法
		onAudioMessage : function(message) {
			handleAudioMessage(message);
		},
		// 收到位置消息的回调方法
		onLocationMessage : function(message) {
			handleLocationMessage(message);
		},
		// 收到文件消息的回调方法
		onFileMessage : function(message) {
			handleFileMessage(message);
		},
		// 收到视频消息的回调方法
		onVideoMessage: function(message) {
			handleVideoMessage(message);
		},
		// 收到联系人订阅请求的回调方法
		onPresence: function(message) {
			handlePresence(message);
		},
		// 收到联系人信息的回调方法
		onRoster: function(message) {
			handleRoster(message);
		},
		// 收到群组邀请时的回调方法
		onInviteMessage: function(message) {
			handleInviteMessage(message);
		},
        onOffline: function () {
            setTimeout(logout, 1000);
        },
		// 异常时的回调方法
		onError: function(message) {
			handleError(message);
		}
	});
	login();
});

// 登录系统时的操作方法
var login = function() {
			// 根据用户名密码登录系统
			conn.open({
				apiUrl : Easemob.im.config.apiURL,
				user : username,
				pwd : password,
				// 连接时提供appkey
				appKey : Easemob.im.config.appkey
			});         
		return false;
};

//处理连接时函数,主要是登录成功后对页面元素做处理
var handleOpen = function(conn) {
	conn.setPresence();
	
	// 从连接中获取到当前的登录人注册帐号名
	curUserId = conn.context.userId;
	
	$('.chat-content').prop('id', username+'-' + curChatUserId);
	if (nick_name != null) {
		$('#chat_title').html(nick_name);
	} else {
		$('#chat_title').html(curChatUserId);
	}
	
	
	//setCurrentContact('huangshun');

	if ( !Easemob.im.Helper.isCanUploadFileAsync && typeof uploadShim === 'function' ) {
		picshim = uploadShim('sendPicInput', 'pic');
		audioshim = uploadShim('sendAudioInput', 'aud');
		fileshim = uploadShim('sendFileInput', 'file');
	}
	
	// 启动心跳
	if (conn.isOpened()) {
		conn.heartBeat(conn);
	}
};

//设置当前显示的聊天窗口div，如果有联系人则默认选中联系人中的第一个联系人，如没有联系人则当前div为null-nouser
var setCurrentContact = function(defaultUserId) {
	showContactChatDiv(defaultUserId);
	curChatUserId = defaultUserId;
};

//显示当前选中联系人的聊天窗口div，并将该联系人在联系人列表中背景色置为蓝色
var showContactChatDiv = function(chatUserId) {
	var contentDiv = getContactChatDiv(chatUserId);
//	if (contentDiv == null) {
//		contentDiv = createContactChatDiv(chatUserId);
//		document.getElementById(msgCardDivId).appendChild(contentDiv);
//	}
	contentDiv.style.display = "block";
	var dispalyTitle = null;// 聊天窗口显示当前对话人名称
	dispalyTitle = "与" + chatUserId + "聊天中";
    $('#chat_title').html(dispalyTitle);
};

//如果当前没有某一个联系人的聊天窗口div就新建一个
var createContactChatDiv = function(chatUserId) {
	var msgContentDivId = curUserId + "-" + chatUserId;
	var newContent = document.createElement("div");
	$(newContent).attr({
		"id" : msgContentDivId,
		"class" : "chat01_content",
		"className" : "chat01_content",
		"style" : "display:none"
	});
	return newContent;
};

//构造当前聊天记录的窗口div
var getContactChatDiv = function(chatUserId) {
	return document.getElementById(curUserId + "-" + chatUserId);
};

var sendText = function() {
	if (textSending) {
		return;
	}
	textSending = true;
	var msgInput = document.getElementById(talkInputId);
	var msg = msgInput.value;
	if (msg == null || msg.length == 0) {
		textSending = false;
		return;
	}
	var to = curChatUserId;
	if (to == null) {
		textSending = false;
		return;
	}
	var options = {
		to : to,
		msg : msg,
		type : "chat"
	};
	

	// easemobwebim-sdk发送文本消息的方法 to为发送给谁，meg为文本消息对象
	conn.sendTextMessage(options);
	// 当前登录人发送的信息在聊天窗口中原样显示
	var msgtext = Easemob.im.Utils.parseLink(Easemob.im.Utils.parseEmotions(encode(msg)));
	appendMsg(curUserId, to, msgtext);
	//turnoffFaces_box();
	msgInput.value = "";
	//msgInput.focus();
	setTimeout(function() {
		textSending = false;
	}, 1000);
};

//显示聊天记录的统一处理方法
var appendMsg = function(who, contact, message, onlyPrompt) {
	if ( !handleChatRoomMessage(contact) ) { return; }
	//if ( !contact.indexOf(chatRoomMark) > -1 ) { return; }

//	var contactUL = document.getElementById("contactlistUL");
//	console.log(contactUL);
	var contactDivId = contact;
	// 消息体 {isemotion:true;body:[{type:txt,msg:ssss}{type:emotion,msg:imgdata}]}
	var localMsg = null;
	if (typeof message == 'string') {
		localMsg = Easemob.im.Helper.parseTextMessage(message);
		localMsg = localMsg.body;
	} else {
		localMsg = message.data;
	}
	var content_message = "";
	
	var headstr = onlyPrompt ? ["<p1>" + message + "</p1>"] : [ "<p1>" + who + "   <span></span>" + "   </p1>",
			"<p2>" + getLoacalTimeString() + "<b></b><br/></p2>" ];
	var header = $(headstr.join(''))
	var messageContent = localMsg,
		flg = onlyPrompt ? 0 : messageContent.length;

	var flag_type = 'right';
	if ( onlyPrompt ) {
		flag_type = 'center';
	} else if (curUserId == who) {
		flag_type = 'right';
	} else {
		flag_type = 'left';
	}
	
	var mydiv = '<div class="content-' + flag_type + '">';
	if(flag_type == 'left') {
		mydiv += '<img class="content-left-header" src="' + head_img + '" />';
	} else if (flag_type == 'right') {
		mydiv += '<img class="content-right-header" src="static/img/head/header2.jpg" />'
	}
	mydiv += '<div class="content-' + flag_type + '-content"><img src="static/img/triangle-' + flag_type + '.png" style="float:'+ flag_type +'; margin-top:13px; ">';
	mydiv += '<div class="content-'+ flag_type +'-content-content">';
	for (var i = 0; i < flg; i++) {
		var msg = messageContent[i];
		var type = msg.type;
		var data = msg.data;
		
		if (type == "emotion") {
			var ele = '<img src="'+ data +'" />';
			mydiv += ele;
		} else if (type == "pic" || type == 'audio' || type == 'video') {
			var fileele = $("<p>" + msg.filename + "</p>");
			fileele.attr("class", "chat-content-p3");
            lineDiv.appendChild(fileele.get(0));
			data.nodeType && lineDiv.appendChild(data);
            $(data).on('load', function(){
                var last = $(msgContentDiv).children().last().get(0);
                last && last.scrollIntoView && last.scrollIntoView();
            });
			if(type == 'audio' && msg.audioShim) {
				var d = $(lineDiv),
					t = new Date().getTime();
				d.append($('<div class="'+t+'"></div>\
					<button class="play'+t+'">播放</button><button style="display:none" class="play'+t+'">暂停</button>'));
			}
		} else {
			var ele = '<span style="max-width:200px;">' + data + '</span>';
			mydiv += ele;
		}
	}
	
	mydiv += '</div></div><div style="clear: both;"></div></div>';
	//$('.chat-content').append(mydiv);
	if (curChatUserId == null) {
		onlyPrompt || setCurrentContact(contact);
		if (time < 1) {
			time++;
		}
	}
	if (curChatUserId && curChatUserId.indexOf(contact) < 0) {
		var contactLi = getContactLi(contactDivId);
		if (contactLi == null) {
			return;
		}
		contactLi.style.backgroundColor = "green";
		var badgespan = $(contactLi).children(".badge");
		if (badgespan && badgespan.length > 0) {
			var count = badgespan.text();
			var myNum = new Number(count);
			myNum++;
			badgespan.text(myNum);
		} else {
			$(contactLi).append('<span class="badge">1</span>');
		}
		//联系人不同分组的未读消息提醒
		var badgespanGroup = $(contactLi).parent().parent().parent().prev()
				.children().children(".badgegroup");
		if (badgespanGroup && badgespanGroup.length == 0) {
			$(contactLi).parent().parent().parent().prev().children()
					.append('<span class="badgegroup">New</span>');
		}
	}
	var msgContentDiv = getContactChatDiv(contactDivId);
	var create = false;
	if (msgContentDiv == null) {
		msgContentDiv = createContactChatDiv(contactDivId);
		create = true;
	}
	if (create) {
		document.getElementById(msgCardDivId).appendChild(msgContentDiv);
	}
	if(type == 'audio' && msg.audioShim) {
		setTimeout(function(){
			playAudioShim(d.find('.'+t), data.currentSrc, t);
		}, 0);
	}
	$(msgContentDiv).append(mydiv);
	//msgContentDiv.scrollTop = msgContentDiv.scrollHeight;
	document.body.scrollTop=document.body.scrollHeight;
	return true;
};

var handleChatRoomMessage = function (contact) {
	if ( contact.indexOf(chatRoomMark) > -1 ) {
		return contact.slice(chatRoomMark.length) === curChatRoomId;
	}
	return true;
};

var getLoacalTimeString = function getLoacalTimeString() {
	var date = new Date();
	var time = date.getHours() + ":" + date.getMinutes() + ":"
			+ date.getSeconds();
	return time;
}

//表情选择div的关闭方法
var turnoffFaces_box = function() {
	$("#wl_faces_box").fadeOut("slow");
};

//easemobwebim-sdk收到文本消息的回调方法的实现
var handleTextMessage = function(message) {
	var from = message.from;// 消息的发送者
	var mestype = message.type;// 消息发送的类型是群组消息还是个人消息
	var messageContent = message.data;// 文本消息体
	// TODO 根据消息体的to值去定位那个群组的聊天记录
	var room = message.to;
	appendMsg(from, from, messageContent);
};

//异常情况下的处理方法
var handleError = function(e) {
	curChatRoomId = null;
	e && e.upload && $('#fileModal').modal('hide');
	if (curUserId == null) {
		alert(e.msg + ",请重新登录");
	} else {
		var msg = e.msg;
		if (e.type == EASEMOB_IM_CONNCTION_SERVER_CLOSE_ERROR) {
			if (msg == "" || msg == 'unknown' ) {
				alert("服务器断开连接,可能是因为在别处登录");
			} else {
				alert("服务器断开连接");
			}
		} else if (e.type === EASEMOB_IM_CONNCTION_SERVER_ERROR) {
			if (msg.toLowerCase().indexOf("user removed") != -1) {
				alert("用户已经在管理后台删除");
			}
		} else {
			alert(msg);
		}
	}
	conn.stopHeartBeat();
};

//easemobwebim-sdk收到表情消息的回调方法的实现，message为表情符号和文本的消息对象，文本和表情符号sdk中做了
//统一的处理，不需要用户自己区别字符是文本还是表情符号。
var handleEmotion = function(message) {
	var from = message.from;
	var room = message.to;
	var mestype = message.type;//消息发送的类型是群组消息还是个人消息
	if (mestype == groupFlagMark || mestype == chatRoomMark) {
		appendMsg(message.from, mestype + message.to, message);
	} else {
		appendMsg(from, from, message);
	}
};
